package com.person.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.person.common.BaseContext;
import com.person.mapper.EmpMapper;
import com.person.pojo.Emp;
import com.person.pojo.PageBean;
import com.person.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;

    //登录
    @Override
    public Emp login(Emp employee) {
        Emp emp = empMapper.login(employee);
        return emp;
    }

    //添加员工
    @Override
    public void addEmp(HttpServletRequest request, Emp emp) {
        emp.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setStatus(1);

//        //通过session，获取当前登录用户的id
//        Long session =(Long) request.getSession().getAttribute("employee");
        //将用户id写入
        emp.setCreateUser(BaseContext.getCurrentId());
        emp.setUpdateUser(BaseContext.getCurrentId());

        log.info("添加员工：{}",emp.toString());

        empMapper.addEmp(emp);
    }

    //分页查询
    @Override
    public PageBean page(Integer page, Integer pageSize, String name) {
        //设置分页参数
        PageHelper.startPage(page,pageSize);

        //查询数据
        List<Emp> emplist = empMapper.pageList(name);
        Page<Emp> p =(Page<Emp>) emplist;

        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());

        return pageBean;
    }



    //更改状态
    @Override
    public void updateById(HttpServletRequest request,Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        //修改状态，的员工的id
        long updateId =(Long) request.getSession().getAttribute("employee");
        emp.setUpdateUser(updateId);
        empMapper.update(emp);
    }

    @Override
    public Emp byId(long id) {
        Emp emp = empMapper.byId(id);
        return emp;
    }
}
